package LC;

/**
 * https://leetcode.com/problems/longest-common-prefix/description/
 * Write a function to find the longest common prefix string amongst an array of strings.
 */
public class LC_014_LongestCommonPrefix_Loop {
    public static void main(String[] args) {
        String[] a = {"abcdwww", "abcoooo"};
        System.out.println(longestCommonPrefix(a));
    }

    private static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) return "";
        int minLen = minLen(strs);
        StringBuilder res = new StringBuilder();
        int idx = 0;
        while (idx < minLen) {
            for (int i = 1; i < strs.length; i++)
                if (strs[i].charAt(idx) != strs[0].charAt(idx))
                    return res.toString();
            res.append(strs[0].charAt(idx));
            idx++;
        }
        return res.toString();
    }

    private static int minLen(String[] strs) {
        int min = Integer.MAX_VALUE;
        for (String str : strs)
            min = Math.min(min, str.length());
        return min;
    }
}